﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.UI;
using Controllers;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace Web
{
    public partial class Examination : Page
    {
        protected int typeId;
        protected EmpBasicInfo ebi;
        protected ApolloOaDataContext ctx;
        protected int answerId;
        protected void Page_Load(object sender, EventArgs e)
        {
            typeId = int.Parse(Request.QueryString["typeId"]);
            ebi = Session["ebi"] as EmpBasicInfo;
            ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
            if(!IsPostBack)
            {
                _getNextQuestion(true);
            }
        }

        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            if(_saveAnswer())
            {
                _getNextQuestion(false);
            }
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            if (_saveAnswer())
            {
                _getNextQuestion(true);
            }
        }

        private bool _saveAnswer()
        {
            string answer = null;
            foreach (RepeaterItem item in rptList.Items)
            {
                HtmlInputCheckBox chk = (HtmlInputCheckBox)item.FindControl("chk");
                if (chk.Checked)
                {
                    answer += chk.Value;
                }
            }
            if(string.IsNullOrEmpty(answer))
            {
                // Define the name and type of the client script on the page.
                String csName = "WarningScript";
                Type csType = this.GetType();

                // Get a ClientScriptManager reference from the Page class.
                ClientScriptManager cs = Page.ClientScript;

                // Check to see if the client script is already registered.
                if (!cs.IsClientScriptBlockRegistered(csType, csName))
                {
                    StringBuilder csText = new StringBuilder();
                    csText.Append(@"<script>alert('请选择该题的答案');</script>");
                    cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
                }
                return false;
            }
            ExamAnswer examAnswer= ctx.ExamAnswers.SingleOrDefault(r => r.EmpId == ebi.Id && r.QuestionId == int.Parse(hdId.Value));
            if(examAnswer==null)
            {
                examAnswer = new ExamAnswer();
                examAnswer.EmpId = ebi.Id;
                examAnswer.QuestionId = int.Parse(hdId.Value);
                ctx.ExamAnswers.InsertOnSubmit(examAnswer);
            }
            examAnswer.Answer = answer;
            ctx.SubmitChanges();

            answerId=examAnswer.Id;
            return true;
        }

        private void _getNextQuestion(bool isNext)
        {
            ExamType examType = ctx.ExamTypes.Single(r => r.Id == typeId);
            lblTitle.InnerText = examType.Title;
            if (examType.StartTime > DateTime.Now || examType.EndTime < DateTime.Now)
            {
                // Define the name and type of the client script on the page.
                String csName = "WarningScript";
                Type csType = this.GetType();

                // Get a ClientScriptManager reference from the Page class.
                ClientScriptManager cs = Page.ClientScript;

                // Check to see if the client script is already registered.
                if (!cs.IsClientScriptBlockRegistered(csType, csName))
                {
                    StringBuilder csText = new StringBuilder();
                    csText.Append(@"<script>alert('考试时间 未到/已过');</script>");
                    cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
                }
            }
            else
            {
                ExamAnswer examAnswer = null;
                ExamQuestion obj=null;
                if (!string.IsNullOrEmpty(hdId.Value))
                {
                    IQueryable<ExamAnswer> examAnswers;
                    if (isNext)
                    {
                        examAnswers = from r in ctx.ExamAnswers where r.EmpId == ebi.Id && r.Id > answerId && (from r2 in ctx.ExamQuestions where r2.TypeId == typeId select r2.Id).Contains(r.QuestionId) orderby r.Id select r;
                    }
                    else
                    {
                        examAnswers = from r in ctx.ExamAnswers where r.EmpId == ebi.Id && r.Id < answerId && (from r2 in ctx.ExamQuestions where r2.TypeId == typeId select r2.Id).Contains(r.QuestionId) orderby r.Id descending select r;
                    }
                    if (examAnswers.Count() > 0)
                    {
                        examAnswer = examAnswers.First();
                        obj = ctx.ExamQuestions.Single(r => r.Id == examAnswer.QuestionId);
                    }
                }
                if(obj==null&&isNext)
                {
                    IQueryable<ExamQuestion> list = from r in ctx.ExamQuestions where r.TypeId == typeId && !(from ea in ctx.ExamAnswers where ea.EmpId == ebi.Id select ea.QuestionId).Contains(r.Id) select r;
                    #region 随机出题--start--
                    int cnt = list.Count();
                    if (cnt > 0)
                    {
                        Random ro = new Random();
                        int skip = ro.Next(cnt);
                        obj = list.Skip(skip).Take(1).First();
                    }
                    #endregion
                }
                if (obj!=null)
                {
                    hdId.Value = obj.Id.ToString();
                    lblQuestion.InnerText = obj.Question + "("+obj.QuestionType + ")";
                    IList<OptionDTO> options = new List<OptionDTO>();
                    if (obj.QuestionType == "判断题")
                    {
                        obj.Options = "A.对\r\nB.错";
                    }
                    char[] opValues = { 'A', 'B', 'C', 'D', 'E', 'F', 'G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
                    string[] textArr = obj.Options.Replace("\r\n", "@").Split('@');
                    for (int i = 0; i < textArr.Length; i++)
                    {
                        char optionStr = opValues[i];
                        if (examAnswer != null && examAnswer.Answer.IndexOf(optionStr)>=0)
                        {
                            options.Add(new OptionDTO { Value = optionStr, Text = textArr[i],IsChecked=true});
                        }
                        else
                        {
                            options.Add(new OptionDTO { Value = optionStr, Text = textArr[i]});
                        }
                    }
                    rptList.DataSource = options;
                    rptList.DataBind();
                }
                else if (!isNext)
                {
                    // Define the name and type of the client script on the page.
                    String csName = "WarningScript";
                    Type csType = this.GetType();

                    // Get a ClientScriptManager reference from the Page class.
                    ClientScriptManager cs = Page.ClientScript;

                    // Check to see if the client script is already registered.
                    if (!cs.IsClientScriptBlockRegistered(csType, csName))
                    {
                        StringBuilder csText = new StringBuilder();
                        csText.Append(@"<script>alert('已到达第一题');</script>");
                        cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
                    }
                }
                else
                {
                    // Define the name and type of the client script on the page.
                    String csName = "WarningScript";
                    Type csType = this.GetType();

                    // Get a ClientScriptManager reference from the Page class.
                    ClientScriptManager cs = Page.ClientScript;

                    // Check to see if the client script is already registered.
                    if (!cs.IsClientScriptBlockRegistered(csType, csName))
                    {
                        StringBuilder csText = new StringBuilder();
                        csText.Append(@"<script>alert('已做完最后一题');location.href='ExamEnd.aspx?typeId="+typeId+"'</script>");
                        cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
                    }
                }
            }
        }
    }
}